import io from 'socket.io-client';
import axios from 'axios';
const socket = io('ws://localhost:9093');
const MSG_READ = 'MSG_READ';
const MSG_RECV = 'MSG_RECV';
const MSG_LIST = 'MSG_LIST';
const MSG_CLEAR = 'MSG_CLEAR';

const initState = {
	chatmsg:[],
	unread:0,
	users:[]
}

export function chat(state=initState,action){
	switch (action.type){
		case MSG_LIST:
			return {...state,users:action.payload.users,chatmsg:action.payload.msgs,unread:action.payload.msgs.filter(v => !v.read && v.to === action.payload.userid).length}
		case MSG_RECV:
			const add = action.payload.msg.to === action.payload.userid ? 1 :0 ;
			return {...state,chatmsg:[...state.chatmsg,action.payload.msg],unread:state.unread + add}
		case MSG_READ:
			return {...state,chatmsg:state.chatmsg.map(v => ({...v,read:v.from === action.payload.from ? true : v.read})),unread:state.unread - action.payload.number}
		case MSG_CLEAR:
			return {...initState}
		default:
			return state;
	}
}


function msgList(data,userid){
	return {type:MSG_LIST,payload:{...data,userid}};
}

function recvmsgSuccess(msg,userid){
	return {type:MSG_RECV,payload:{msg,userid}};
}
function msgRead(from,userid,number){
	return {type:MSG_READ,payload:{from,userid,number}};
}

export function readmsg(from){
	return (dispatch,getState) => {
		axios.post('/user/readmsg',{from})
			.then(res =>{
				if (res.status === 200) {
					if (res.data.code === 0) {
						dispatch(msgRead(from,getState().user._id,res.data.content.number));
					}
				} 
			})
	}
}

export function clearmsg(){
	return {type:MSG_CLEAR};
}
export function getMsgList(){
	return (dispatch,getState) => {
		axios.get('/user/msglist')
			.then(res =>{
				if (res.status === 200) {
					if (res.data.code === 0) {
						console.log(res.data.content);
						dispatch(msgList(res.data.content,getState().user._id));
					}
				} 
			});
	};
}

export function sendmsg(from,to,content){
	return dispatch => {
		socket.emit('sendmsg',{from,to,content});
	}
}

export function recvmsg(from,to,content){
	return (dispatch,getState) => {
		socket.on('recvmsg',function(data){
			dispatch(recvmsgSuccess(data,getState().user._id));
		});
	}
}